[CF852E]Casinos and travel

2019-11-15
Codeforces

题意

给出一棵树,定义$f(t)$为以t为根,从根到叶子节点的所有链上白格子数为偶数,的黑白染色方案数

求$\sum_{i=1}^n f(i)$

题解

先写个Dp,发现每一棵有根树的答案为:

令$x$为n-叶子节点的个数,则$f(t)=2^x$

$O(n)$求和即可

调试记录

想到结论就好了不会证也没事

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <cstdio>
const int maxn = 1e5 + 5;
const int mo = 1e9 + 7;
using namespace std;
int ind[maxn], n, c, ans;
int pow(int x, int t){
int res = 1; x %= mo;
while (t > 0){
if (t & 1) res = 1ll * res * x % mo;
x = 1ll * x * x % mo;
t >>= 1;
}
return res;
}
int main(){
scanf("%d", &n);
for (int u, v, i = 1; i < n; i++){
scanf("%d%d", &u, &v);
ind[u]++, ind[v]++;
}
for (int i = 1; i <= n; i++)
if (ind[i] > 1) ++c;
int P = pow(2, c);
for (int i = 1; i <= n; i++)
if (ind[i] == 1) ans = (ans + 2ll * P % mo) % mo;
else ans = (ans + P) % mo;
printf("%d\n", ans);
return 0;
}